package cn.gailvlun.gll.presentation.emotion;

import android.app.Activity;
import android.app.Dialog;
import android.arch.lifecycle.ViewModelProviders;
import android.content.Context;
import android.content.Intent;
import android.databinding.ViewDataBinding;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityOptionsCompat;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.ImageView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.KeyboardUtils;
import com.github.markzhai.recyclerview.BaseViewAdapter;
import com.github.markzhai.recyclerview.BindingViewHolder;
import com.scwang.smartrefresh.layout.api.RefreshHeader;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import cn.gailvlun.gll.databinding.ItemEmotionSquareEmotionBinding;
import cn.gailvlun.gll.databinding.ItemEmotionSquareHeaderBinding;
import cn.gailvlun.gll.net.GsonUtil;
import cn.gailvlun.gll.net.HttpMethods;
import cn.gailvlun.gll.net.HttpSubscriber;
import cn.gailvlun.gll.net.ListRes;
import cn.gailvlun.gll.net.emotion.Emotion;
import cn.gailvlun.gll.net.emotion.RefreshReq;
import cn.gailvlun.gll.net.emotion.UserActiveDateRes;
import cn.gailvlun.gll.presentation.emotion.core.BaseAdapter;
import cn.gailvlun.gll.presentation.emotion.core.BaseViewModel;
import cn.gailvlun.gll.presentation.emotion.core.ImmersionHeaderActivity;
import cn.gailvlun.gll.presentation.emotion.core.ViewModelFactory;
import cn.gailvlun.gll.presentation.emotion.edit.EmotionRecordActivity;
import cn.gailvlun.gll.presentation.emotion.photo.GalleryActivity;
import cn.gailvlun.gll.presentation.emotion.util.Util;
import cn.gailvlun.gll.presentation.emotion.widget.CollapseTextView;
import cn.gailvlun.gll.util.DialogUtil;
import cn.gailvlun.gll.util.FileUtil;
import cn.gailvlun.gll.util.IsEmpty;
import cn.gailvlun.gll.util.RxUtil;
import cn.gailvlun.gll.util.SPUtil;
import cn.gailvlun.gll.widget.ImageGroupView;
import cn.gailvlun.gll.widget.NavigationBarView;
import io.reactivex.functions.Consumer;
import rx_activity_result2.Result;

import static cn.gailvlun.gll.presentation.emotion.photo.GalleryFragmentKt.VIEW_NAME_IMAGE;



public class EmotionSquareActivity extends ImmersionHeaderActivity {

    @NotNull
    @Override
    public SubclassEnum getSubclassEnum() {
        return SubclassEnum.Square;
    }

    public static void openActivity(Context context) {
        Intent intent = new Intent(context, EmotionSquareActivity.class);
        context.startActivity(intent);
    }

    @NotNull
    @Override
    public BaseAdapter<?> initAdapter() {
        return new EmotionSquareAdapter(mContext);
    }

    @NotNull
    @Override
    public BaseViewModel initViewModel() {

        return ViewModelProviders.of(this,
                ViewModelFactory.Companion.getInstance(this, (BaseAdapter<Object>) getAdapter()))
                .get(EmotionSquareViewModel.class);
    }

    @Override
    protected void initComponent() {
        super.initComponent();



        getAdapter().setDecorator(new BaseViewAdapter.Decorator() {
            @Override
            public void decorator(BindingViewHolder holder, final int position, int viewType) {
                final ViewDataBinding itemBinding = holder.getBinding();

                
                if (itemBinding instanceof ItemEmotionSquareEmotionBinding) {

                    ((ItemEmotionSquareEmotionBinding) itemBinding).llTextAndImage.igvEmotionImage.setOnPhotoClickListener(new ImageGroupView.OnPhotoClickListener() {
                        @Override
                        public void onItemClick(ImageView iv, List<String> photos, int position) {
                            ActivityOptionsCompat options = ActivityOptionsCompat.makeSceneTransitionAnimation(mContext, ((ItemEmotionSquareEmotionBinding) itemBinding).llTextAndImage.igvEmotionImage, VIEW_NAME_IMAGE + "-" + position);
                            GalleryActivity.Companion.openActivity(mContext, new ArrayList<>(photos), position, null);
                        }
                    });
                    final Emotion emotion = (Emotion) getAdapter().getData().get(position);
                    ((ItemEmotionSquareEmotionBinding) itemBinding).rlToolBar.ctvFunction.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            ((EmotionSquareViewModel) getViewModel()).showFunction(view, emotion);
                        }
                    });

                    ((ItemEmotionSquareEmotionBinding) itemBinding).llTextAndImage.ctvContent.setOnCollapseTextListener(new CollapseTextView.OnCollapseTextListener() {
                        @Override
                        public void onCollapseText(View view) {
                            Rect r = new Rect();
                            getBinding().rvEmotionList.getChildVisibleRect(itemBinding.getRoot(), r, null);
                            if (r.top < 20) {
                                linearLayoutManager.scrollToPositionWithOffset(position, getBinding().nbv.getHeight());
                            }
                        }
                    });

                    itemBinding.getRoot().getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                        @Override
                        public void onGlobalLayout() {
                            ((ItemEmotionSquareEmotionBinding) itemBinding).ivMostLight.setX(getRandon().nextInt(itemBinding.getRoot().getWidth()));
                            ((ItemEmotionSquareEmotionBinding) itemBinding).ivMostLight.setY(getRandon().nextInt(itemBinding.getRoot().getHeight()));
                            ((ItemEmotionSquareEmotionBinding) itemBinding).ivSecondLight.setX(getRandon1().nextInt(itemBinding.getRoot().getWidth()));
                            ((ItemEmotionSquareEmotionBinding) itemBinding).ivSecondLight.setY(getRandon1().nextInt(itemBinding.getRoot().getHeight()));
                            ((ItemEmotionSquareEmotionBinding) itemBinding).ivLightDark.setX(getRandon2().nextInt(itemBinding.getRoot().getWidth()));
                            ((ItemEmotionSquareEmotionBinding) itemBinding).ivLightDark.setY(getRandon2().nextInt(itemBinding.getRoot().getHeight()));
                            itemBinding.getRoot().getViewTreeObserver().removeOnGlobalLayoutListener(this);
                        }
                    });
                }
                
                if (itemBinding instanceof ItemEmotionSquareHeaderBinding) {

                }
            }
        });
    }

    @Override
    public void onMenuClick(@NotNull NavigationBarView nbv) {
        EmotionRecordActivity.openActivity(mContext, new Consumer<Result<Activity>>() {
            @Override
            public void accept(Result<Activity> activityResult) throws Exception {
                if (activityResult.resultCode() == Activity.RESULT_OK) {
                    getBinding().rvEmotionList.smoothScrollToPosition(0);
                    if (KeyboardUtils.isSoftInputVisible(mContext)) {
                        KeyboardUtils.hideSoftInput(mContext);
                    }
                    RefreshReq req = EmotionSquareActivity.this.getReq();
                    String stringExtra = activityResult.data().getStringExtra("extra_emotion_obj");
                    Emotion emotion = GsonUtil.getGson().fromJson(stringExtra, Emotion.class);
                    getAdapter().add(1, emotion, EmotionSquareAdapter.Type.CONTENT.ordinal());
                }

            }
        });
    }

    @Override
    public void onHeaderPulling(@Nullable RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {
        super.onHeaderPulling(header, percent, offset, headerHeight, extendHeight);
        ((EmotionSquareViewModel) getViewModel()).getScaleXObservable().set(Math.max(percent, 1f));
        ((EmotionSquareViewModel) getViewModel()).getScaleYObservable().set(Math.max(percent, 1f));
        binding.nbv.setAlpha(0f);
        binding.nbv.setVisibility(View.GONE);
    }

    @Override
    public void onHeaderReleasing(@Nullable RefreshHeader header, float percent, int offset, int headerHeight, int extendHeight) {
        super.onHeaderReleasing(header, percent, offset, headerHeight, extendHeight);
        if (percent > 1) {
            ((EmotionSquareViewModel) getViewModel()).getScaleXObservable().set(percent);
            ((EmotionSquareViewModel) getViewModel()).getScaleYObservable().set(percent);
        }
        
        if (getState() != RefreshState.RELEASED) {
            binding.nbv.setAlpha(1f);
            binding.nbv.setVisibility(View.VISIBLE);
        }
    }

    private Dialog pd;

    @Override
    protected void loadData(@Nullable Bundle savedInstanceState) {
        pd = DialogUtil.showIndeterminate(mContext);
        getAdapter().add(null, EmotionSquareAdapter.Type.HEADER.ordinal());

        getAdapter().add(null, EmotionSquareAdapter.Type.EMPTY.ordinal());
        super.loadData(savedInstanceState);
    }

    @Override
    public void getData(@NonNull final RefreshReq req) {
        HttpMethods.getEmotionService().emotionListG(
                req.getId(),
                req.getDirection(),
                15,
                req.getFilterEnum() == null ? null : req.getFilterEnum().name())
                .compose(RxUtil.<ListRes<Emotion>>applyScheduler())
                .subscribe(new HttpSubscriber<ListRes<Emotion>>() {
                    @Override
                    protected void onSuccess(ListRes<Emotion> response) {
                        pd.dismiss();
                        getBinding().invalidateAll();
                        getBinding().srl.setEnableLoadmore(response.isNext());
                        if (response.getResults().size() > 0) {
                            int lastIndex = response.getResults().size() - 1;
                            req.setId(response.getResults().get(lastIndex).getId());
                        }
                        if (req.isLoadMore()) {
                            getAdapter().addAll(response.getResults(), EmotionSquareAdapter.Type.CONTENT.ordinal());
                        } else {
                            getBinding().invalidateAll();
                            getAdapter().clear();
                            getAdapter().add(null, EmotionSquareAdapter.Type.HEADER.ordinal());

                            if (IsEmpty.list(response.getResults())) {
                                getAdapter().add(null, EmotionSquareAdapter.Type.EMPTY.ordinal());
                            } else {
                                getActiveData(response.getResults());
                                getAdapter().addAll(response.getResults(), EmotionSquareAdapter.Type.CONTENT.ordinal());

                            }
                        }
                        getBinding().srl.finishLoadmore(0);
                        getBinding().srl.finishRefresh(0);

                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable ListRes<Emotion> response, int code) {
                        pd.dismiss();
                        DialogUtil.showError(mContext, errMsg);
                        getBinding().srl.finishLoadmore(0);
                        getBinding().srl.finishRefresh(0);
                    }
                });

    }

    private void getActiveData(final List<Emotion> results) {
        HttpMethods.getEmotionService()
                .getUserActiveDate()
                .compose(RxUtil.<UserActiveDateRes>applyScheduler())
                .compose(mContext.<UserActiveDateRes>bindToLifecycle())
                .subscribe(new HttpSubscriber<UserActiveDateRes>() {
                    @Override
                    protected void onSuccess(UserActiveDateRes userActiveDateRes) {

                        SPUtil.put(SPUtil.USER, "emo_privileged", userActiveDateRes.getEmo_privileged());

                        SPUtil.put(SPUtil.USER, BaseViewModel.Companion.getPREF_COVER_URI(), userActiveDateRes.getBackground());
                        getViewModel().getCoverUri().set(userActiveDateRes.getBackground());

                        ((EmotionSquareViewModel) getViewModel()).getTextObservable().set(Util.getMyEmotionCount(userActiveDateRes.getDays(), userActiveDateRes.getCount()).toString());
                    }

                    @Override
                    protected void onFailure(String errMsg, @Nullable UserActiveDateRes response, int code) {
                        DialogUtil.showError(mContext, errMsg);
                    }
                });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileUtils.deleteAllInDir(FileUtil.INSTANCE.getIMAGE_CACHE_DIR());
    }
}
